package com.lanyun.oss.config;

import com.lanyun.oss.enums.OssTypeEnum;
import com.lanyun.oss.service.AliyunOssStorageService;
import com.lanyun.oss.service.MinioStorageService;
import com.lanyun.oss.service.StorageService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/14
 */
@Configuration
@ConfigurationProperties(prefix = "storage")
public class StorageConfig {

    @Value("${storage.type}")
    private String type;

    @Value("${storage.aliyun-oss.endpoint}")
    private String aliOssEndpoint;

    @Value("${storage.aliyun-oss.access-key-id}")
    private String aliOssAccessKeyId;

    @Value("${storage.aliyun-oss.access-key-secret}")
    private String aliOssAccessKeySecret;

    @Value("${storage.aliyun-oss.bucket-name}")
    private String aliOssBucketName;

    @NestedConfigurationProperty
    private AliyunOssConfig aliyunOss;

    @NestedConfigurationProperty
    private MinioConfig minio;

    @Bean
    public StorageService storageService() {
        if (type == null || type.trim().isEmpty()) {
            throw new IllegalArgumentException("Configuration property 'storage.type' is missing or empty.");
        }
        OssTypeEnum ossType = OssTypeEnum.fromType(type);
        if (OssTypeEnum.ALIYUN_OSS.equals(ossType)) {
            return new AliyunOssStorageService(
                    aliOssEndpoint,
                    aliOssAccessKeyId,
                    aliOssAccessKeySecret,
                    aliOssBucketName);
        } else if (OssTypeEnum.MINIO.equals(ossType)) {
            return new MinioStorageService(
                    minio.getEndpoint(),
                    minio.getAccessKey(),
                    minio.getSecretKey(),
                    minio.getBucketName());
        } else {
            throw new IllegalArgumentException("Unsupported storage type: " + type);
        }
    }

    @Data
    public static class AliyunOssConfig {
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
    }

    @Data
    public static class MinioConfig {
        private String endpoint;
        private String accessKey;
        private String secretKey;
        private String bucketName;
    }
}
